import json
import datetime
from django.http import JsonResponse, HttpResponse
from rest_framework import generics, views
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import Book, Borrowed
from .seralizers import BooksSerializer, BorrowedSerializer
from .filters import BooksFilter, BorrowFilter
from .tasks import add


# Create your views here.
class BooksListAPIView(generics.ListAPIView):
    queryset = Book.objects.all().order_by("id")  # 查询数据集根据id进行排序
    serializer_class = BooksSerializer
    filterset_class = BooksFilter


class BooksAPIView(views.APIView):
    @staticmethod
    def get_object(pk):
        return get_object_or_404(Book, pk=pk)

    @staticmethod
    def get(request, pk):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = Book.objects.filter(id=pk).values().first()
            res["code"] = 200
            res["message"] = "success"
            res["data"] = data
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        finally:
            return Response(res)

    @staticmethod
    def put(request, pk):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = json.loads(request.body)
            Book.objects.filter(id=pk).update(**data)
            res["code"] = 200
            res["message"] = "编辑成功"
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        finally:
            return Response(res)

    @staticmethod
    def delete(request, pk):
        res = {"code": 400, "message": "", "data": None}
        try:
            Book.objects.filter(id=pk).delete()
            res["code"] = 200
            res["message"] = "删除成功"
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        finally:
            return Response(res)


def add_book(request):
    res = {"code": 400, "message": "", "data": None}
    try:
        data = json.loads(request.body)
        now = datetime.datetime.today()
        today = now.strftime("%Y-%m-%d %H:%M:%S")
        data['add_date'] = today
        Book.objects.create(**data)
        res["code"] = 200
        res["message"] = "新增成功"
    except Exception as e:
        res["code"] = 500
        res["message"] = "服务器错误：" + str(e)
    finally:
        return JsonResponse(res)


class BorrowListAPIView(generics.ListAPIView):
    queryset = Borrowed.objects.all().order_by("id")
    serializer_class = BorrowedSerializer
    filterset_class = BorrowFilter


class BorrowedAPIView(views.APIView):
    @staticmethod
    def get_object(pk):
        return get_object_or_404(Book, pk=pk)

    @staticmethod
    def get(request, pk):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = Borrowed.objects.filter(id=pk).values().first()
            res["code"] = 200
            res["message"] = "success"
            res["data"] = data
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        finally:
            return Response(res)

    @staticmethod
    def put(request, pk):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = json.loads(request.body)
            Borrowed.objects.filter(id=pk).update(**data)
            res["code"] = 200
            res["message"] = "编辑成功"
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        finally:
            return Response(res)

    @staticmethod
    def delete(request, pk):
        res = {"code": 400, "message": "", "data": None}
        try:
            Borrowed.objects.filter(id=pk).delete()
            res["code"] = 200
            res["message"] = "删除成功"
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        finally:
            return Response(res)


def add_borrower(request):
    res = {"code": 400, "message": "", "data": None}
    try:
        data = json.loads(request.body)
        now = datetime.datetime.today()
        today = now.strftime("%Y-%m-%d %H:%M:%S")
        data['borrow_date'] = today
        Borrowed.objects.create(**data)
        res["code"] = 200
        res["message"] = "新增成功"
    except Exception as e:
        res["code"] = 500
        res["message"] = "服务器错误：" + str(e)
    finally:
        return JsonResponse(res)


def test_celery(request):
    add.delay(3333, 533333)
    return HttpResponse("Celery works")
